<template>
  <div class="edit-box">
    <el-form :model="form" :inline="true" label-position="top" :rules="formRules" ref="ruleForm">
      <el-form-item label="合同编号">
        <el-input v-model="form.contractId"></el-input>
      </el-form-item>
      <el-form-item label="所属类别" prop="allTypeId">
        <el-cascader
          v-model="form.allTypeId"
          :show-all-levels="false"
          :options="typeList"
          :props="{value: 'id',label: 'name', checkStrictly: true, emitPath: false}"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="关联客户/供应商">
        <el-select
          v-model="form.customerId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteCustomerList"
          :loading="loading"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.customerName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联项目">
        <el-select
          v-model="form.projectsId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteProjectList"
          :loading="loading"
        >
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="签订日期">
        <el-date-picker
          v-model="form.signDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="合同期限" width="100%">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item> -->
      <el-form-item label="项目负责人" prop="leadingId">
        <el-select
          v-model="form.leadingId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteUserList"
          :loading="loading"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="item.userName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 列表数据 -->
      <div class="list-box">
        <div class="rateState">
          <el-select v-model="form.haveTax" placeholder="请选择" style="width: 120px">
            <el-option
              v-for="item in options"
              :key="item.val"
              :label="item.label"
              :value="item.val"
            ></el-option>
          </el-select>
        </div>
        <el-table :data="form.productContractMids" max-height="500px" stripe class="table-list">
          <el-table-column label="产品/服务">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.productId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteProductList"
                :loading="loading"
              >
                <el-option
                  v-for="item in productList"
                  :key="item.id"
                  :label="item.productName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="leadingName" label="单价">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.unitPrice"
                @input="scope.row.total = reSum(scope.row)"
                @change="scope.row.unitPrice = formatterNum(scope.row.unitPrice)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="leadingName" label="单位">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.count"
                @input="scope.row.total = reSum(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="折扣">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.discount"
                @input="scope.row.total = reSum(scope.row)"
                @change="scope.row.discount = formatterNum(scope.row.discount)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="金额">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.total" :disabled="true"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="税率">
            <template slot-scope="scope">
              <el-select v-model="scope.row.tax" placeholder="请选择">
                <el-option
                  v-for="item in rateOptions"
                  :key="item.val"
                  :label="item.label"
                  :value="item.val"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="delProduct(scope.row)">
                <i class="el-icon-delete"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-btn-box">
          <el-link type="primary" @click="addProduct" :underline="false">
            <i class="el-icon-plus"></i> 添加产品
          </el-link>
        </div>
        <div class="submit-box">
          <p>小计：{{ subtotal }} 元</p>
          <p>税额：{{ rateSum }} 元</p>
          <p>合计：{{ sumMoney }} 元</p>
        </div>
        <div class="ys-box" v-if="ysShow">

          <div class="add-btn-box">
            <h3 class="fl" style="margin-right:15px">应收款项</h3>
          </div>
          <el-table :data="form.receivables" max-height="500px" stripe class="table-list">
            <el-table-column type="index" width="150px" :index="indexMethod"></el-table-column>
            <el-table-column label="预计缴费时间">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.receivablesDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="预计缴费金额（元）">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.receivablesMoney"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="delReceive(scope.row)">
                  <i class="el-icon-delete"></i>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="add-btn-box">
            <el-link type="primary" @click="addReceive" :underline="false">
              <i class="el-icon-plus"></i> 添加应收
            </el-link>
          </div>
        </div>
      </div>
      <el-form-item label="合同文本" style="width: 100%">
        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.remark"></el-input>
      </el-form-item>
      <el-form-item label="合同文本">
        <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('changeState',false)">取 消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </div>
  </div>
</template>
<script>
import * as math from 'mathjs'
import { update, findById } from '@/api/contract'
import { findByNameLike as findCustomerList } from '@/api/customer'
import { findByNameLike as findProjectList } from '@/api/project'
import { findByNameLike as findProductList } from '@/api/product'
import { getListByName } from '@/api/user'
import { findList } from '@/api/type'
export default {
  data() {
    return {
      loading: false,
      date: [],
      ysShow: false,
      fileList: [],
      form: {
        id: '',
        companyId: this.$store.state.user.companyId,
        contractId: '',
        signDate: '',
        startDate: '',
        endDate: '',
        contractType: '',
        customerId: '',
        projectsId: '',
        leadingId: '',
        rateSum: '',
        totalSum: '',
        remark: '',
        haveTax: 0,
        taxMoney: 0,
        receivables: [],
        productContractMids: []
      },
      productList: [],
      projectList: [],
      customerList: [],
      typeList: [],
      userOptions: [],
      options: [
        {
          val: 0,
          label: '含税'
        },
        {
          val: 1,
          label: '不含税'
        }
      ],
      rateOptions: [
        {
          val: 0,
          label: '0%'
        },
        {
          val: 0.03,
          label: '3%'
        },
        {
          val: 0.05,
          label: '5%'
        },
        {
          val: 0.06,
          label: '6%'
        },
        {
          val: 0.07,
          label: '7%'
        },
        {
          val: 0.09,
          label: '9%'
        },
        {
          val: 0.1,
          label: '10%'
        },
        {
          val: 0.11,
          label: '11%'
        },
        {
          val: 0.13,
          label: '13%'
        },
        {
          val: 0.16,
          label: '16%'
        },
        {
          val: 0.17,
          label: '17%'
        }
      ],
      formRules: {
        leadingId: [
          { required: true, message: '请选择负责人', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    subtotal() {
      return this.form.productContractMids.reduce((sum, res) => {
        return math.add(sum, res.total).toFixed(2)
      }, 0)
    },
    rateSum() {
      return this.form.productContractMids.reduce((sum, res) => {
        return math
          .add(
            sum,
            math.divide(
              math.multiply(res.total, res.tax),
              math.subtract(1, res.tax)
            )
          )
          .toFixed(2)
      }, 0)
    },
    sumMoney() {
      let sum = this.subtotal
      if (this.haveTax === 1) {
        sum = math.add(this.subtotal, this.rateSum).toFixed(2)
      }
      return sum
    }
  },
  beforeDestroy() {
    this.$off('reload')
    this.$off('changeState')
  },
  methods: {
    initDialogData(id) {
      this.remoteUserList('')
      this.remoteProductList('')
      this.remoteCustomerList('')
      this.remoteProjectList('')
      this.initTypeOptions()
      findById(id).then(res => {
        this.form = res.data
        this.ysShow = this.form.contractType !== 2
        // this.date.push(this.form.startDate)
        // this.date.push(this.form.endDate)
      })
    },
    initTypeOptions() {
      findList(this.form.companyId, 3).then(res => {
        this.typeList = res.data
      })
    },
    // 自定义索引
    indexMethod(index) {
      return '第' + (index + 1) + '次'
    },
    reSum(obj) {
      return math
        .subtract(math.multiply(obj.unitPrice, obj.count), obj.discount)
        .toFixed(2)
    },
    formatterNum(val) {
      return parseFloat(val).toFixed(2)
    },
    // 获取用户列表
    remoteUserList(query) {
      this.loading = true
      let params = { companyId: this.form.companyId, userName: query }
      getListByName(params).then(res => {
        this.loading = false
        this.userOptions = res.data
      })
    },
    // 获取产品列表
    remoteProductList(query) {
      this.loading = true
      let params = { companyId: this.form.companyId, productName: query }
      findProductList(params).then(res => {
        this.loading = false
        this.productList = res.data
      })
    },
    // 获取客户列表
    remoteCustomerList(query) {
      this.loading = true
      let params = { companyId: this.form.companyId, customerName: query }
      findCustomerList(params).then(res => {
        this.loading = false
        this.customerList = res.data
      })
    },
    // 获取项目列表
    remoteProjectList(query) {
      this.loading = true
      let params = { companyId: this.form.companyId, projectsName: query }
      findProjectList(params).then(res => {
        this.loading = false
        this.projectList = res.data
      })
    },
    // 添加一行产品数据
    addProduct() {
      this.form.productContractMids.push({
        id: '',
        contractId: this.form.id,
        productId: '',
        count: 1,
        unitPrice: 0,
        total: 0,
        discount: 0,
        tax: 0,
        unit: ''
      })
    },
    // 删除一行产品数据
    delProduct(row) {
      this.from.productContractMids.splice(
        this.from.productContractMids.indexOf(row),
        1
      )
    },
    // 添加一行应收数据
    addReceive() {
      this.form.receivables.push({
        receivablesDate: '',
        receivablesMoney: 0,
        contractId: this.form.id,
        companyId: this.form.companyId
      })
    },
    // 删除一行应收数据
    delReceive(row) {
      this.form.receivables.splice(this.form.receivables.indexOf(row), 1)
    },
    submit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.form.rateSum = this.rateSum
          this.form.totalSum = this.sumMoney
          // this.form.startDate = this.date[0]
          // this.form.endDate = this.date[1]
          update(this.form).then(res => {
            if (res.success) {
              this.$emit('reload')
              this.$emit('changeState', false)
              this.$message.success(res.message)
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          return false
        }
      })
    },
    // 以下附件上传相关，根据情况删减
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  }
}
</script>
<style lang="scss" scoped>
.edit-box {
  padding: 0 50px;
  overflow-y: auto;
}
.dialog-footer {
  text-align: right;
}
.el-form--inline .el-form-item {
  width: 30%;
}
.list-box {
  margin-bottom: 15px;
}
.add-btn-box {
  height: 50px;
  line-height: 50px;
}
.submit-box {
  line-height: 50px;
  font-size: 18px;
  text-align: right;
}
.rateState {
  text-align: right;
}
</style>
